import request from '../request'
import type { ProjectProgressResponse, ProjectTimelineResponse } from '../../types'

/**
 * 项目进度 API 服务
 */
export const progressApi = {
    /**
     * 根据项目ID获取项目完成进度
     * @param projectId 项目ID
     * @returns 项目进度数据
     */
    async getProjectProgress(projectId: number): Promise<ProjectProgressResponse> {
        const response = await request.get<ProjectProgressResponse>(`/progress/project/${projectId}`)
        return response.data
    },

    /**
     * 获取项目进度快照（带错误处理）
     * @param projectId 项目ID
     * @returns 项目进度数据或错误信息
     */
    async getProjectProgressSafe(projectId: number) {
        try {
            const data = await this.getProjectProgress(projectId)
            return {
                success: true,
                data,
                error: null
            }
        } catch (error: any) {
            return {
                success: false,
                data: null,
                error: error.message || '获取项目进度失败'
            }
        }
    },

    /**
     * 计算项目总体完成率
     * @param projectId 项目ID
     * @returns 总体完成率（0-1之间的数值）
     */
    async getOverallCompletionRate(projectId: number): Promise<number> {
        const response = await this.getProjectProgress(projectId)
        const typeProgressData = response.data.type_progress_data

        if (!typeProgressData || Object.keys(typeProgressData).length === 0) {
            return 0
        }

        const totalTarget = Object.values(typeProgressData).reduce((sum, item) => sum + (item?.target_quantity || 0), 0)
        const totalCompleted = Object.values(typeProgressData).reduce((sum, item) => sum + (item?.completed_quantity || 0), 0)

        return totalTarget > 0 ? totalCompleted / totalTarget : 0
    },

    /**
     * 获取项目质量指标摘要
     * @param projectId 项目ID
     * @returns 质量指标摘要
     */
    async getQualityMetricsSummary(projectId: number) {
        const response = await this.getProjectProgress(projectId)
        const qualityMetrics = response.data.quality_metrics

        return {
            totalBacklinks: qualityMetrics.total_backlinks,
            avgQualityScore: qualityMetrics.avg_quality_score,
            indexRate: qualityMetrics.index_status.index_rate,
            highQualityRate: (qualityMetrics.da_distribution.da_50_70 + qualityMetrics.da_distribution.da_70_plus) /
                (qualityMetrics.da_distribution.da_0_30 + qualityMetrics.da_distribution.da_30_50 +
                    qualityMetrics.da_distribution.da_50_70 + qualityMetrics.da_distribution.da_70_plus) || 0
        }
    },

    /**
     * 获取项目完成度时间线数据
     * @param projectId 项目ID
     * @param period 时间周期 ('daily' | 'weekly' | 'monthly')
     * @returns 项目时间线数据
     */
    async getProjectTimeline(projectId: number): Promise<any> {
        const response = await request.get<ProjectTimelineResponse>(`/progress/timeline/${projectId}`)
        return response.data
    },

    /**
     * 获取项目时间线数据（带错误处理）
     * @param projectId 项目ID
     * @returns 项目时间线数据或错误信息
     */
    async getProjectTimelineSafe(projectId: number) {
        try {
            const response = await request.get(`/progress/timeline/${projectId}`)
            console.log('Timeline API Response:', response) // 添加调试日志
            return {
                success: true,
                data: response.data, // 根据你提供的API响应，数据直接在 response.data 中
                error: null
            }
        } catch (error: any) {
            console.error('Timeline API Error:', error) // 添加错误日志
            return {
                success: false,
                data: null,
                error: error.message || '获取项目时间线失败'
            }
        }
    }
}